<script lang="ts" setup>
import {onBeforeMount, reactive, ref} from "vue";
import Edit from './edit.vue';
import DataTable from '@/components/data-table/index.vue';
import {getDictTrim, getRoleList} from "@/api/system";
import {service} from "@/utils";
import {env} from '@/utils'

const dataTableRef = ref<InstanceType<typeof DataTable>>();
const editRef = ref<InstanceType<typeof Edit>>();
const params = ref({
    username: undefined,
    deptName: undefined,
    status: '',
})
const columns = ref([
    {prop: "username", label: "用户名", align: "left", width: "120", tooltip: true, sortable: true, fixed: 'left'},
    {prop: "firstname", label: "姓名", align: "left", width: "120", tooltip: true, fixed: 'left'},
    {prop: "deptName", label: "所属部门", align: "left", minWidth: "250", tooltip: true},
    {prop: "email", label: "邮箱", align: "left", minWidth: "250", tooltip: true},
    {prop: "mobile", label: "手机号", align: "right", width: "150", tooltip: true},
    {prop: "sex", label: "性别", width: "90", tag: true, visible: false},
    {prop: "status", label: "状态", width: "90", tag: true},
    {prop: 'birthDate', 'label': '出生日期', width: "150", visible: false},
    {prop: 'address', 'label': '家庭住址', width: "350", tooltip: true, visible: false},
    {prop: "lastLoginIp", label: "最后登录IP地址", width: "150", visible: false},
    {prop: "lastLoginTime", label: "最后登录时间", width: "190"},
    {prop: "lastLoginLocation", label: "最后登录地址", width: "190", tooltip: true, visible: false},
    {
        type: "action", width: "280", maxCollapseButtons: 2,
        render: [
            {auth: 'user:update', onClick: ({row}: any) => onEdit(row)},
            {auth: 'user:delete', onClick: ({row}: any) => onDelete(row), type:'danger'},
            {auth: 'user:reset', onClick: ({row}: any) => onReset(row)},
        ]
    },
])
const enumData = reactive<{[key:string]: any}>({});

// 新增&修改
function onEdit(row?: any) {
    editRef.value?.open({
        data: row,
        confirm: (resolve: (value: any)=> void, form: any, operate: AxiosMethod) => {
            if (env.APP_VERSION === '3.0.0') {
                service[operate]('/user', JSON.stringify(form), {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(({code}) => {
                    if (code === 200) {
                        dataTableRef.value?.refresh();
                    }
                    resolve(code);
                })
            } else {
                service[operate]('/user', form).then(({code}) => {
                    if (code === 200) {
                        dataTableRef.value?.refresh();
                    }
                    resolve(code);
                })
            }
        },
    }, enumData);
}

// 删除
function onDelete (data: any) {
    const names = Array.isArray(data) ? data.map((item: any) => item.username) : [data.username];
    service.confirm(`确定对用户名[${names.join(',')}]进行${names.length === 1 ? '删除' : '批量删除'}操作,该操作不可逆?`, {
        url: '/user',
        data: {usernames: names},
        success: dataTableRef.value?.refresh
    })
}
// 重置密码
function onReset (row: any) {
    service.confirm(`确定对用户名[${row.username}]进行密码重置操作(重置后密码: 1234qwer)?`, {
        url: '/user/password/reset',
        type: 'put',
        data: {usernames: row.username}
    })
}

async function onLoadEnumsData () {
    Promise.all([getDictTrim('sys_user'), getRoleList()]).then((rs) => {
        let data = rs[0].data;
        Object.keys(data).forEach((field: string) => {
            enumData[field] = Array.from(data[field]).map((item: any) => {
                item.effect = 'dark';
                switch (item.value) {
                    case '0':item.type = 'warning';break
                    case '1':item.type = 'success';break
                }
                return item;
            });
        })

        data = rs[1].data;
        if (env.APP_VERSION === '3.0.0') {
            enumData['roles'] = data.rows;
        } else {
            enumData['roleId'] = data.rows.map((item: any) => ({label: item.alias, value: String(item.roleId)}));
        }
    })
}

onBeforeMount(() => onLoadEnumsData())
</script>
<template>
    <main-page>
        <data-table ref="dataTableRef" :columns="columns" :enums="enumData" v-model:params="params" primary-key="userId" api="/user" selection select-on-row-click>
            <template #button="{selections}">
                <el-button v-auth="'user:add'" @click="onEdit()"/>
                <el-button v-auth="'user:delete'" @click="onDelete(selections)" :disabled="!(selections.length > 1)" type="danger"/>
            </template>
            <template #search>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="params.username"/>
                </el-form-item>
                <el-form-item label="部门" prop="deptName">
                    <el-input v-model="params.deptName"/>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="params.status" :empty-values="[null, undefined]">
                        <el-option label="全部" value=""/>
                        <el-option v-for="(item, index) in enumData['status']" :key="index" :label="item.label" :value="item.value"/>
                    </el-select>
                </el-form-item>
            </template>
        </data-table>

        <edit ref="editRef"/>
    </main-page>
</template>

